package com.google.code.p.restrpc.message;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author dz
 */
public class MessageSender implements MessageAction {
    
    private static final Log logger = LogFactory.getLog(MessageSender.class);
    
    private MessageAction action;
    
    /**
     * 
     */
    private boolean fastBack = true;
    
    public MessageSender(MessageAction action) {
        super();
        this.action = action;
    }
    
    public MessageSender(MessageAction action, boolean fastBack) {
        super();
        this.action = action;
        this.fastBack = fastBack;
    }
    
    public void execute(MessageContext context) {
//        logger.debug("MessageSender start...");
        if (fastBack) {
            try {
                action.execute(context);
            }
            catch (Exception e) {
                if (logger.isErrorEnabled()) {
                    logger.error("Message send failed!The reason is " + e.getMessage(),
                                 e);
                }
                logger.warn("The fastback mode enabled,and action will re-send later!");
                
                context.getQueue().addLazyMessage(context.getMessage());
            }
            finally {
//                logger.debug("MessageSender end!");
            }
            return;
        }
        action.execute(context);
    }
    
}
